//
//  VipCenterBookDetailVC.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/4/1.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "VipCenterBookDetailVC.h"
#import "PriceSelectedView.h"
#import "MineAPIManager.h"
#import "BookDetailTableViewCell.h"

@interface VipCenterBookDetailVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *tableHeaderView;

@property(nonatomic ,strong)UIButton *buyBtn;

@property(nonatomic ,strong)NSDictionary *data;

@property(nonatomic ,strong)NSArray *bookList;

@property(nonatomic ,strong)NSString *bookid;

@property(nonatomic ,assign)NSInteger row;

@property(nonatomic ,assign)NSInteger page;

@property(nonatomic ,assign)NSInteger pageSize;
@end

@implementation VipCenterBookDetailVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:rgba(245, 245, 245, 1)] backgroundColor:rgba(245, 245, 245, 1) shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(51, 51, 51, 1),NSFontAttributeName:MFontWithSize(18)} enableScrollEdgeAppearance:NO];
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"服务详情";
    [self setBackButtonIsHidden:NO];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = rgba(245, 245, 245, 1);
    self.buyBtn.superview.y = self.tableView.height + self.tableView.y;
  
    [self createRightBarButtonItem];
    if (self.bookid.length == 0) {
        [self.tableView.mj_header beginRefreshing];
    }else{
     
        [self getVipInfo];
    }
}
- (void)getVipInfo
{
    [MineAPIManager GetVipInfoWithParam:@{@"id":self.bookid} result:^(NSDictionary * _Nonnull dic) {
        self.data = dic[@"data"][@"info"];
        self.tableHeaderView = nil;
        [self.tableView setTableHeaderView:self.tableHeaderView];
        [self.tableView.mj_header beginRefreshing];
    }];
}
- (void)createRightBarButtonItem
{
    UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 44)];
    UIImage *img = IMAGENAMED(@"ic_mine_phone");
    [button setImage:img forState:UIControlStateNormal];
    [button setImage:img forState:UIControlStateHighlighted];
    button.width = img.size.width;
    [button addTarget:self action:@selector(phoneClick) forControlEvents:UIControlEventTouchUpInside];
   
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItems =@[item];
}
- (void)refresh
{
    self.page = 1;
    self.pageSize = 15;
    [self getBookList];
}
-(void)LoadMore
{
    self.page = self.page + 1;
    [self getBookList];
}
- (void)getBookList
{
    NSMutableDictionary *dic1 = @{@"page":[NSNumber numberWithInteger:self.page],@"pageSize":[NSNumber numberWithInteger:self.pageSize]}.mutableCopy;
    if (self.data[@"grade_type"]) {
        [dic1 setObject:self.data[@"grade_type"] forKey:@"grade"];
    }
    [MineAPIManager getBookListWithParam:@{} result:^(NSDictionary * _Nonnull dic) {
        self.bookList = dic[@"data"];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)phoneClick
{
    [MethodTool callWithMobileNumber:lApp.mobileCustomer];
}
- (void)buyBtnAction
{
    if (lApp.isVip == 1) return;
    if (VALIDARRAY(self.data[@"pramsjson"])) {
        NSArray *array = self.data[@"pramsjson"];
        NSDictionary *dic = array[self.row];
        NSMutableDictionary *parame = @{@"amount":dic[@"price"],@"vip_id":self.data[@"id"]}.mutableCopy;

        [MineAPIManager CreateOrderListWithParam:parame result:^(NSDictionary * _Nonnull dic) {
            if (dic[@"msg"]) {
                [SVProgressHUD showSuccessWithStatus:dic[@"msg"]];
            }
            
        }];
    }
    
}

#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BookDetailTableViewCell"];
    
    if (!cell)
    {
        cell = [[BookDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"BookDetailTableViewCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    cell.isLast = (self.bookList.count == indexPath.row + 1);
    cell.data = self.bookList[indexPath.row];
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.bookList.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 114;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 62;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth,62)];
    UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(10, 0, lScreenWidth - 20,62)];
    [header addSubview:bg];
    [header setBackgroundColor:lClearColor];
    [bg setBackgroundColor:lWhiteColor];
    [bg setCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadius:15];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, lScreenWidth - 40, 24)];
    titleLabel.font = MFontWithSize(16);
    titleLabel.text =  @"书籍列表";
    [titleLabel setTextAlignment:NSTextAlignmentLeft];
    titleLabel.textColor = rgba(51, 51, 51, 1);
    [bg addSubview:titleLabel];
    
    UILabel *titleSubLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, titleLabel.bottom + 10, lScreenWidth - 40, 16)];
    titleSubLabel.font = MFontWithSize(14);
    titleSubLabel.text =[NSString stringWithFormat: @"此服务包含的书籍列表（共%lu本）",(unsigned long)self.bookList.count];
    [titleSubLabel setTextAlignment:NSTextAlignmentLeft];
    titleSubLabel.textColor = rgba(142, 142, 142, 1);
    [bg addSubview:titleSubLabel];
    return header;
}
#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, lTopBarHeight, lScreenWidth, lScreenHeight - lBottomDangerousAreaHeight - 55 - lTopBarHeight) style:UITableViewStyleGrouped];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        //_tableView.bounces = NO;
        [_tableView setBackgroundColor:lClearColor];
        [_tableView setSeparatorColor:lWhiteColor];
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 10, 0, 0)];
        [_tableView setTableHeaderView:self.tableHeaderView];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self refresh];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self LoadMore];
        }];
    }
    
    return _tableView;
}

-(UIButton *)buyBtn
{
    if (!_buyBtn)
    {
        _buyBtn = [UIButton new];
        _buyBtn.frame =CGRectMake(0, 0, lScreenWidth - 20, 45);
       
        _buyBtn.selected =NO;
        
        [_buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
        if (lApp.isVip == 1) {
            [_buyBtn setTitle:@"已开通" forState:UIControlStateNormal];
        }
       
        [_buyBtn setTitleColor:lWhiteColor forState:UIControlStateNormal];
        [_buyBtn.titleLabel setFont:MFontWithSize(18)];
        [_buyBtn addTarget:self action:@selector(buyBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _buyBtn.backgroundColor = lClearColor;
        UIView *btnView =[[UIView alloc] initWithFrame:CGRectMake(10, 65, lScreenWidth - 20, 45)];
        [btnView setAllCornersWithCornerRadius:22.5];
        // gradient
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,lScreenWidth - 20,45);
        gl.startPoint = CGPointMake(1, 0.5);
        gl.endPoint = CGPointMake(0, 0.5);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:41/255.0 green:241/255.0 blue:156/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:2/255.0 green:161/255.0 blue:249/255.0 alpha:1.0].CGColor];
        gl.locations = @[@(0), @(1.0f)];
        [btnView.layer addSublayer:gl];
        [btnView addSubview:self.buyBtn];
        [self.view addSubview:btnView];
    }
    
    return _buyBtn;
}
-(UIView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        
        _tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth,72)];
        _tableHeaderView.backgroundColor = lClearColor;
        UIView *bookView = [[UIView alloc] init];
        bookView.frame = CGRectMake(10,10,lScreenWidth - 20,152);
        bookView.backgroundColor = lWhiteColor;
        [bookView setAllCornersWithCornerRadius: 15];
        [_tableHeaderView addSubview:bookView];
        
        UIImageView *bookImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10,10, 85, 102)];
        
      //  [headerImageView sd_setImageWithURL:[NSURL URLWithString:self.avatar]];
        [bookView addSubview:bookImgView];
    
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(105,10, bookView.width - 115,22)];
        titleLabel.font = SFontWithSize(16);
        if (self.data[@"name"]) {
            titleLabel.text = self.data[@"name"];
        }
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        titleLabel.textColor = rgba(51, 51, 51, 1);
        
        UILabel * typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.x, titleLabel.bottom + 10, titleLabel.width, 20)];
        typeLabel.font = RFontWithSize(14);
        typeLabel.text = @"适用于：";
        if (self.data[@"grade_type"]) {
            NSString *class = [self.data[@"grade_type"] intValue]?@"小学":[self.data[@"grade_type"] intValue] == 2?@"初中":@"高中";
            typeLabel.text = [NSString stringWithFormat:@"适用于：%@",class];
        }
      
        [typeLabel setTextAlignment:NSTextAlignmentLeft];
        typeLabel.textColor = rgba(142, 142, 142, 1);
        [bookView addSubview:titleLabel];
        [bookView addSubview:typeLabel];
        
        UILabel * desTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.x,typeLabel.bottom + 10, typeLabel.width, 20)];
        desTitleLabel.font = RFontWithSize(14);
        desTitleLabel.text =@"描   述：";
        [desTitleLabel setTextAlignment:NSTextAlignmentLeft];
        desTitleLabel.textColor = rgba(142, 142, 142, 1);
        [desTitleLabel sizeToFit];
        desTitleLabel.height = 20;
        
        UILabel *desLabel = [[UILabel alloc] initWithFrame:CGRectMake(desTitleLabel.right, desTitleLabel.y, typeLabel.width - desTitleLabel.width, 20)];
        desLabel.font = RFontWithSize(14);
        [desLabel setTextAlignment:NSTextAlignmentLeft];
        desLabel.textColor = rgba(142, 142, 142, 1);
        desLabel.numberOfLines = 2;
        [bookView addSubview:desLabel];
        [bookView addSubview:desTitleLabel];
        if (self.data[@"desc"]) {
            desLabel.text = self.data[@"desc"];
          double height   = [MethodTool getTextHeightWithStr:desLabel.text font:desLabel.font ViewWidth:desLabel.width];
            if (height > 20) {
                height = height > 40? 40:height;
                desLabel.height = height;
            }
        }
       
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(105,desLabel.bottom + 10, bookView.width - 115,22)];
        dateLabel.font = RFontWithSize(14);
        dateLabel.text = @"已购买：";
//        if (self.data[@"delete_time"]) {
//            typeLabel.text = self.data[@"delete_time"];
//        }
        dateLabel.hidden = YES;
        [dateLabel setTextAlignment:NSTextAlignmentLeft];
        dateLabel.textColor = rgba(142, 142, 142, 1);
        [bookView addSubview:dateLabel];
        bookView.height = dateLabel.bottom + 10;
        
        UIView *priceView = [[UIView alloc] init];
        priceView.frame = CGRectMake(10,bookView.bottom + 10,lScreenWidth - 20,124);
        priceView.backgroundColor = lWhiteColor;
        [priceView setAllCornersWithCornerRadius: 15];
        [_tableHeaderView addSubview:priceView];
      
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,10, bookView.width - 40,22)];
        priceLabel.font = SFontWithSize(16);
        priceLabel.text = @"价格";
        [priceLabel setTextAlignment:NSTextAlignmentLeft];
        priceLabel.textColor = rgba(51, 51, 51, 1);
        [priceView addSubview:priceLabel];
        if (VALIDARRAY(self.data[@"pramsjson"])) {
            NSArray *array = self.data[@"pramsjson"];
            if (array.count > 0) {
                PriceSelectedView *view = [[PriceSelectedView alloc] initWithFrame:CGRectMake(0, 42, lScreenWidth - 20, 72)];
                view.data = array;
                self.row = 0;
                view.block = ^(NSInteger row) {
                    self.row = row;
                };
                [priceView addSubview:view];
            }
        }
        _tableHeaderView.height = priceView.bottom + 10;
    }
    
    return _tableHeaderView;
}
- (void)setParaObject:(NSObject *)paraObject
{
    
    if ([paraObject isKindOfClass:[NSDictionary class]]) {
        self.data = (NSDictionary *)paraObject;
    }
    if ([paraObject isKindOfClass:[NSString class]]) {
        self.bookid = (NSString *)paraObject;
    }
}
- (void)setRow:(NSInteger)row
{
    _row = row;
    NSArray *array = self.data[@"pramsjson"];
    NSDictionary *dic = array[row];
    [self.buyBtn setTitle:[NSString stringWithFormat:@"立即购买（%.2f)元",[dic[@"price"] doubleValue]] forState:UIControlStateNormal];
    if (lApp.isVip == 1) {
        [_buyBtn setTitle:@"已开通" forState:UIControlStateNormal];
    }
}
@end
